from flask import Flask, render_template, request, redirect, url_for, session
from datetime import datetime
import ssl
app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 用于加密会话数据

# 用户的登录验证 (用户名和密码示例，实际使用中应连接数据库)
valid_users = {
    "gua": "zhuasen1",
    "user2": "password2"
}

# 模拟消息存储
messages = []

@app.route('/')
def index():
    return redirect(url_for('fake'))

@app.route('/fake', methods=['GET', 'POST'])
def fake():
    if request.method == 'POST':
        # 从表单中获取用户输入
        name = request.form.get('name')
        email = request.form.get('email')
        message = request.form.get('message')

        # 检查是否符合条件
        if name == 'a' and email == 'aa' and message == 'aaa':
            # 跳转到登录页面
            return redirect(url_for('login'))

        # 不符合条件，继续留在当前页面或提供提示
        return render_template('fake.html', error="输入值不正确，请重新输入。")

    # 默认是 GET 请求，显示表单页面
    return render_template('fake.html')


# 登录页面
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        # 验证用户
        if valid_users.get(username) == password:
            session['username'] = username  # 存储用户的用户名到会话
            return redirect(url_for('send_message'))  # 登录成功后跳转到消息发送页面
        else:
            return render_template('login.html', error="用户名或密码错误")
    return render_template('login.html')

# 信息发送页面
@app.route('/send_message', methods=['GET', 'POST'])
def send_message():
    if 'username' not in session:
        return redirect(url_for('login'))  # 用户未登录时跳转到登录页面

    username = session['username']
    
    if request.method == 'POST':
        message = request.form['message']
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        ip = request.remote_addr
        
        # 存储消息信息
        messages.append({
            'timestamp': timestamp,
            'ip': ip,
            'username': username,
            'message': message
        })

        return redirect(url_for('send_message'))  # 发送成功后刷新页面

    return render_template('send_message.html', username=username)

# 展示接收到的消息
@app.route('/display_message')
def display_message():
    if 'username' not in session:
        return redirect(url_for('login'))  # 用户未登录时跳转到登录页面
    
    # 限制访问仅限本机
    if request.remote_addr != '127.0.0.1' and request.remote_addr != 'localhost':
        return "访问被拒绝，仅限本机访问", 403  # 如果访问者不是本机，则返回访问拒绝

    return render_template('display_message.html', messages=messages)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=443, ssl_context=('cert.pem', 'key.pem'))
